<template>
  <el-form-item label="字体样式">
    <div>
      <el-checkbox v-if="editorForm.fontWeight" v-model="fontWeight" size="small" class="font-checkbox" @change="changeFontWeight">
        <template #default>
          <i class="iconfont" title="加粗">&#xec83;</i>
        </template>
      </el-checkbox>
      <el-checkbox v-if="editorForm.italic" v-model="italic" size="small" class="font-checkbox" @change="changeItalic">
        <template #default>
          <i class="iconfont" title="倾斜">&#xe7dd;</i>
        </template>
      </el-checkbox>
      <el-checkbox v-if="editorForm.underline" v-model="underline" size="small" class="font-checkbox" @change="changeUnderline">
        <template #default>
          <i class="iconfont" title="下划线">&#xec85;</i>
        </template>
      </el-checkbox>
    </div>
  </el-form-item>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'

const { editorForm, domList, backUpdate } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref(new Set())
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.fontWeight.value`, `${editorForm.value._key}.italic.value`, `${editorForm.value._key}.underline.value`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.add(element)
      }
    })
  })
}

const fontWeight = ref(false)
const italic = ref(false)
const underline = ref(false)

const changeFontWeight = value => {
  if (value) {
    editorForm.value.fontWeight.value = 600
  } else {
    editorForm.value.fontWeight.value = 400
  }
  bindDom.value.forEach(element => {
    element.style.fontWeight = editorForm.value.fontWeight.value
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

const changeItalic = value => {
  if (value) {
    editorForm.value.italic.value = 'italic'
  } else {
    editorForm.value.italic.value = ''
  }
  bindDom.value.forEach(element => {
    element.style.fontStyle = editorForm.value.italic.value
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

const changeUnderline = value => {
  if (value) {
    editorForm.value.underline.value = 'underline'
  } else {
    editorForm.value.underline.value = ''
  }
  bindDom.value.forEach(element => {
    element.style.textDecoration = editorForm.value.underline.value
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

onMounted(() => {
  if (editorForm.value.fontWeight?.value) {
    fontWeight.value = true
  }
  if (editorForm.value.italic?.value) {
    italic.value = true
  }
  if (editorForm.value.underline?.value) {
    underline.value = true
  }
  initDomMapping()
})
</script>

<style lang="scss" scoped>
::v-deep .font-checkbox.el-checkbox .el-checkbox__input {
  display: none;
}
</style> 